var sha1=require('sha1');
var express=require('express');
var router=express.Router();

var UserModel=require('../models/users');
var checkNotLogin=require('../middlewares/check').checkNotLogin;

//GET /signin 登陆页面
router.get('/',checkNotLogin,function(req,res,next){
    res.render('signin');
});

//POST /siginin 用户登陆
router.post('/',checkNotLogin,function(req,res,next){
    var name=req.fields.name;
    var password=req.fields.password;

    UserModel.getUserByName(name)
        .then(function(user){
            if(!user){
                req.flash('error','用户不存在');
                return res.redirect('back');
            }
            //匹配密码是否正确
            if(sha1(password)!==user.password){
                req.flash('error','用户名或密码错误');
                return res.redirect('back');
            };
            req.flash('success','登陆成功');
            //用户信息写入session
            delete user.password;
            req.redirect('/posts')
        })
        .catch(next)
});

module.exports=router;